package edu.zju.gis.dbfg.queryserver.controller;

import edu.zju.gis.dbfg.common.Result;
import edu.zju.gis.dbfg.queryserver.model.SearchResult;
import edu.zju.gis.dbfg.queryserver.service.SpatialQueryService;
import edu.zju.gis.dbfg.queryserver.tool.FormatUtil;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/geomQuery")
public class SpatialQueryController {
    @Autowired
    private SpatialQueryService spatialQueryService;

    @RequestMapping(value = "/identify/{indexName}", method = RequestMethod.POST)
    public Result identify(@PathVariable String indexName, String lon, String lat) {
        SearchResult result = spatialQueryService.selectByPoint(indexName, Double.valueOf(lon), Double.valueOf(lat));
        return Result.success().setBody(FormatUtil.SearchResult2Record(result, true));
    }

    @RequestMapping(value = "/area/{indexName}", method = RequestMethod.POST)
    public Result area(@PathVariable String indexName, @RequestBody String requestBody) {
        JSONArray req = new JSONArray(requestBody);
        List<double[]> cors = new ArrayList<>();
        for (int i = 0; i < req.length(); i++) {
            double[] lonlat = new double[2];
            lonlat[0] = req.getJSONObject(i).getDouble("lon");
            lonlat[1] = req.getJSONObject(i).getDouble("lat");
            cors.add(lonlat);
        }
        SearchResult result = spatialQueryService.selectByPolygon(indexName, cors);
        return Result.success().setBody(FormatUtil.SearchResult2Records(result, true));
    }
}
